package com.neo.tiny.middle.file.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.neo.tiny.admin.entity.SysConfig;
import com.neo.tiny.admin.sysConfig.bean.StorageClientConfig;
import com.neo.tiny.admin.sysConfig.interfaces.SysConfigService;
import com.neo.tiny.common.common.ResResult;
import com.neo.tiny.common.constant.FileConstants;
import com.neo.tiny.middle.file.vo.StorageReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/11/17 20:55
 */
@Slf4j
@Api(tags = "存储配置控制器")
@RestController
@AllArgsConstructor
@RequestMapping("/storage/config")
public class StorageConfigController {

    private final SysConfigService sysConfigService;


    @ApiOperation("保存配置")
    @PostMapping("/save")
    public ResResult save(@RequestBody StorageReqVO req) {

        log.info("保存配置入参：{}", req);
        // 校验
        if (req.getMinIo().getEnable() && req.getLocal().getEnable()) {
            return ResResult.failed("同时只能开启一个配置");
        }

        StorageClientConfig config = BeanUtil.copyProperties(req, StorageClientConfig.class);

        StorageClientConfig storeConfig = sysConfigService.loadStoreConfig(FileConstants.STORAGE_CONFIG);
        if (BeanUtil.isEmpty(storeConfig)) {
            SysConfig sysConfig = new SysConfig();
            sysConfig.setConfigKey(FileConstants.STORAGE_CONFIG);
            sysConfig.setConfigValue(JSONUtil.toJsonStr(config));
            sysConfig.setConfigName(FileConstants.STORAGE_CONFIG);
            sysConfigService.save(sysConfig);
        } else {
            sysConfigService.update(new LambdaUpdateWrapper<SysConfig>()
                    .set(SysConfig::getConfigValue, JSONUtil.toJsonStr(config))
                    .eq(SysConfig::getConfigKey, FileConstants.STORAGE_CONFIG));
        }
        return ResResult.success(true);
    }

    @ApiOperation("获取存储配置配置")
    @GetMapping("/get")
    public ResResult<StorageClientConfig> get() {

        SysConfig config = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, FileConstants.STORAGE_CONFIG));

        Assert.isFalse(config == null, "配置为空");
        String configValue = config.getConfigValue();
        StorageClientConfig storageClientConfig = JSONUtil.toBean(configValue, StorageClientConfig.class);

        return ResResult.success(storageClientConfig);
    }

}
